<template>
  <div class="map-page">
    <!-- 顶部导航 -->
    <div class="nav-header">
      <div class="back" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        <span>返回</span>
      </div>
      <div class="title">{{ pageTitle }}</div>
    </div>

    <!-- 地图容器 -->
    <div id="map" class="map-container"></div>

    <!-- 搜索结果面板 -->
    <div class="result-panel" v-if="searchResults.length">
      <div class="panel-header">
        <span>{{ pageTitle }}</span>
        <span class="count">{{ searchResults.length }}个结果</span>
      </div>
      <div class="result-list">
        <template v-if="type === 'bus'">
          <div v-for="item in searchResults" 
               :key="item.id" 
               class="result-item"
               @click="showOnMap(item)">
            <div class="bus-line">{{ item.name }}</div>
            <div class="bus-info">
              <span>首末站: {{ item.start }} - {{ item.end }}</span>
              <span>运营时间: {{ item.time }}</span>
            </div>
          </div>
        </template>
        
        <template v-if="type === 'school'">
          <div v-for="item in searchResults" 
               :key="item.id" 
               class="result-item"
               @click="showOnMap(item)">
            <div class="school-name">{{ item.name }}</div>
            <div class="school-info">
              <span>{{ item.type }}</span>
              <span>距离: {{ item.distance }}米</span>
            </div>
          </div>
        </template>

        <template v-if="type === 'community'">
          <div v-for="item in searchResults" 
               :key="item.id" 
               class="result-item"
               @click="showOnMap(item)">
            <div class="community-name">{{ item.name }}</div>
            <div class="community-info">
              <span>{{ item.address }}</span>
              <span>均价: {{ item.price }}元/㎡</span>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 加载中 -->
    <el-loading v-model="loading" fullscreen />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const type = ref(route.query.type)
const map = ref(null)
const searchResults = ref([])
const loading = ref(false)

// 页面标题
const pageTitle = computed(() => {
  const titles = {
    bus: '公交找房',
    school: '学校找房',
    community: '找小区'
  }
  return titles[type.value] || '地图找房'
})

// 初始化地图
const initMap = () => {
  map.value = new TMap.Map('map', {
    center: new TMap.LatLng(39.908802, 116.397502),
    zoom: 12,
    pitch: 0,
    rotation: 0
  })

  // 添加定位控件
  map.value.addControl(new TMap.Control.Location({
    position: 'RB'
  }))
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 加载房源标记
    await loadHouses()

    // 根据类型加载不同数据
    switch (type.value) {
      case 'bus':
        await loadBusStations()
        break
      case 'school':
        await loadSchools()
        break
      case 'community':
        await loadCommunities()
        break
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 加载房源
const loadHouses = async () => {
  try {
    const response = await fetch('http://127.0.0.1:8000/api/houses/')
    const houses = await response.json()
    addMarkers(houses, 'house')
  } catch (error) {
    console.error('加载房源失败:', error)
  }
}

// 加载公交站点
const loadBusStations = async () => {
  const searchService = new TMap.service.Search({
    key: 'FSEBZ-TNJCT-QHVXM-VTJSO-5YBZ5-OFFFH'
  })
  
  const result = await searchService.search({
    keyword: '公交站',
    boundary: 'nearby(39.908802,116.397502,2000)',
    pageSize: 20,
    orderby: '_distance'
  })
  
  searchResults.value = result.data
  addMarkers(result.data, 'bus')
}

// 加载学校
const loadSchools = async () => {
  const searchService = new TMap.service.Search({
    key: 'FSEBZ-TNJCT-QHVXM-VTJSO-5YBZ5-OFFFH'
  })
  
  const result = await searchService.search({
    keyword: '学校',
    boundary: 'nearby(39.908802,116.397502,2000)',
    pageSize: 20,
    orderby: '_distance'
  })
  
  searchResults.value = result.data
  addMarkers(result.data, 'school')
}

// 加载小区
const loadCommunities = async () => {
  const searchService = new TMap.service.Search({
    key: 'FSEBZ-TNJCT-QHVXM-VTJSO-5YBZ5-OFFFH'
  })
  
  const result = await searchService.search({
    keyword: '小区',
    boundary: 'nearby(39.908802,116.397502,2000)',
    pageSize: 20,
    orderby: '_distance'
  })
  
  searchResults.value = result.data
  addMarkers(result.data, 'community')
}

// 添加标记
const addMarkers = (items, type) => {
  const markers = new TMap.MultiMarker({
    map: map.value,
    styles: {
      [type]: new TMap.MarkerStyle({
        width: 25,
        height: 25,
        anchor: { x: 12.5, y: 12.5 },
        src: `/markers/${type}.png`
      })
    },
    geometries: items.map(item => ({
      id: item.id,
      styleId: type,
      position: new TMap.LatLng(item.latitude, item.longitude)
    }))
  })

  markers.on('click', (evt) => {
    const item = items.find(i => i.id === evt.geometry.id)
    showOnMap(item)
  })
}

// 在地图上显示位置
const showOnMap = (item) => {
  map.value.setCenter(new TMap.LatLng(item.latitude, item.longitude))
  map.value.setZoom(15)
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 生命周期钩子
onMounted(() => {
  initMap()
  loadData()
})

onUnmounted(() => {
  if (map.value) {
    map.value.destroy()
  }
})
</script>

<style scoped>
.map-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.nav-header {
  height: 50px;
  background: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  z-index: 1;
}

.back {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.title {
  margin-left: 20px;
  font-weight: bold;
}

.map-container {
  flex: 1;
  position: relative;
}

.result-panel {
  position: absolute;
  top: 60px;
  right: 20px;
  width: 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  max-height: calc(100vh - 80px);
  overflow-y: auto;
}

.panel-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-list {
  padding: 10px;
}

.result-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.result-item:hover {
  background: #f5f7fa;
}

.bus-line, .school-name, .community-name {
  font-weight: bold;
  margin-bottom: 8px;
}

.bus-info, .school-info, .community-info {
  font-size: 14px;
  color: #666;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.count {
  color: #409EFF;
}
</style> 